<!--
 * @Author: chen jiao 
 * @Date: 2021-07-07 16:22:44
 * @LastEditTime: 2021-11-23 19:39:43
 * @LastEditors: Please set LastEditors
 * @Description: 会员标签-添加会员标签
 * @FilePath: \ebc-admin\src\views\member\MemberInfo\Label.vue
-->
<template>
  <div class="addLabel">
    <div class="content-box">
        <edit-from-list
          ref="form" 
          :edit-list="editList"   
          :rules="rules" 
          validate-on-rule-change
          >
        </edit-from-list>
     
      <!-- 自动标签 -->
      <div class="autoTag" v-show="getRadioVal === '0'" >
        <el-form ref="form1"  label-width="120px" >
          <el-form-item 
            v-for="item in getdata"
            :key="item.key"
            :label="item.label">
            <el-button icon="el-icon-circle-plus" @click="openAndset(item.key,item.label)"></el-button>
            <span class="tag-box">
              <el-tag class="tag-item"
                v-for="tag in item.tags"
                :key="tag.name"
                type="success"
                effect="dark"
                closable
                @close="handleClose(tag, tag.name)"
                >
                {{tag.name}}
              </el-tag>
            </span>
          
          </el-form-item>
        </el-form>
      </div>
      <!-- 手动标签 -->
          <edit-form
           ref="form"
           v-show="getRadioVal === '1'"
          :form="tagInfo"
          :edit-list="labelForm2"
          :rules="rules"
          validate-on-rule-change
          ></edit-form>
      <!-- 打开弹窗 -->
        <el-dialog
          :title="`编辑${title}`"
          :visible.sync="dialogVisible"
           width="40%"
         >
         <!-- 根据不同的表单数据展示不同的内容 -->
              <edit-form-style
                v-show="flagAsBtn == 'userProperty'"
                :form-list="userProperty"
              /> 
               <edit-form-style
                v-show="flagAsBtn == 'actionProperty'"
                :form-list="actionProperty"
              />
               <edit-form-style
                v-show="flagAsBtn == 'businessProperty'"
                :form-list="businessProperty"
              />
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="save()">保 存</el-button>
              </span>
        </el-dialog>

      <!-- 页面底部 -->
      <template>
        <el-row>
          <el-button type="primary" @click="submitForm()">保 存</el-button>
          <el-button @click="goBack()">返 回</el-button>
        </el-row>
      </template>
    </div>
  </div>
</template>

<script>
// 组件
import EditFromList from '@/components/admin/edit-from-list.vue'
import EditFormStyle from '.././MemberInfo/component/edit-form-style.vue'
import EditForm from '@/components/admin/edit-form.vue'
// 数据封装
import { labelForm1,labelForm2 ,setTagsProto ,rules ,editListHanlder} from '../config/setTag.config.js'
import { asyncApiFun } from '@/utils/utils'

// 接口
import { tagsDetail , addOrUpdate } from '@/api/member.js'


  export default {
    name:'addLabel',
    components:{
      EditFromList,
      EditFormStyle,
      EditForm
    },
    data(){
      return {
        ...setTagsProto(),
        editListHanlder,
        rules,
        editList:editListHanlder(true), 
        labelForm1,
        labelForm2,
        dialogVisible:false,
        flagAsBtn:''  ,//标签类型属性标记
        title:''  ,    //添加标签框title
        tagInfo:{},
        init:true,   //重置editList数据标识
        tags: {},     //当前显示的标签
        tagProperty:{}  //标签属性值
      }
    },
    created(){
      this.initTagdetail()
      this.editList = editListHanlder(this.init)
    },
    methods:{
      //初始化会员标签详情
     async initTagdetail(){
        const { id } = this.$route.query
        if (id === undefined) return
        const [res] = await asyncApiFun( tagsDetail, id )
        if (res) {
         
          if(res.data && res.data.expire == 0 ) {res.data.expire = res.data.expire == 0 ? '永久' : res.data.expire}
          this.tagInfo = res.data ? res.data : {}
          this.editList.forEach(item => {
            for (let key in res.data)
              if(key == item.key) item.value = this.tagInfo[key]
          })
          // 添加标签时不处理
          if(!this.tagInfo.tagProperty) return
          // 自动标签属性
          this.tagProperty = JSON.parse(res.data.tagProperty)
          Object.keys(this.tagProperty).forEach(item => {
          const obj = this.tagProperty[item]
           
          // 遍历数据封装
          this[item].filter( propVal =>{  

          // 接口返回的对象筛到新对象
            for (let key in obj){
                // 这个item.key指age等  
              if(propVal.key == key){
                  obj[key].forEach( i => {
                      const tag = {
                              operator:i.operator,
                              term:i.term,
                              name:i.name,
                              key
                        }
                        // 标签属性显示处理 
                        if(propVal.key == 'city') {
                          // console.log(i)
                              tag.name = i.cityName
                              tag.areaProvinceId = i.areaProvinceId,
                              tag.areaCityId = i.areaCityId,
                              tag.areaDistrictId = i.areaDistrictId
                        }
                        else if( propVal.key == 'gender') {
                          tag.name = tag.term =='0'?'女':'男'
                        }
                        else {
                          tag.name = propVal.label + tag.operator + tag.term
                         }
                       
                        propVal.dynamicTags && propVal.dynamicTags.push(tag)
                        // console.log(propVal.dynamicTags) 
                    })
                  }       
                }
             })
          })  
        }
      },
      // 打开标签类型设置框
      openAndset(key,title){
        // 获取当前设置按钮的key
        this.flagAsBtn = key
        // 设置当前弹窗的标题
        this.title = title
        this.dialogVisible = true
      },
      // 设置标签后保存
      save(){
        this.dialogVisible = false;
      },
      // 删除标签
      handleClose(tags, name){
        if (tags.delete) return tags.delete()
            tags.p.dynamicTags = tags.p.dynamicTags.filter(item => {
              if (item.name instanceof Array) {
                return item.name[1] !== name;
              } else {
                return item.name !== name;
              }
          })
      },
      // 页面保存
      async  submitForm(){
        this.$refs.form.ruleFrom()
        // 遍历计算属性得到新的属性json
        const _tagProperty = {}
        // 遍历封装的数据
        this.getdata.forEach(item => {
          // 整理接口数据结构
          _tagProperty[item.key] = {}
          // 遍历每个属性的标签数组
          item.tags.forEach(tags =>{
            // 给标签属性加数组
            _tagProperty[item.key][tags.key] = []
          }) 
          item.tags.forEach( tags => { 
          // 遍历tags
            const objTag = {
                    operator: tags.operator,
                    term:tags.term=='女'? '0':
                         tags.term=='男'? '1': tags.term ,      
                  } 
                  if(tags.key =='city') {
                    // console.log(tags)
                     objTag.cityName = tags.cityName,
                     objTag.areaProvinceId= tags.areaProvinceId,
                     objTag.areaCityId = tags.areaCityId,
                     objTag.areaDistrictId = tags.areaDistrictId
                    
                  }
                   _tagProperty[item.key][tags.key].push(objTag)
            })
               
        })
        // 转成json字符串
         const tagProperty = JSON.stringify(_tagProperty)
         this.tagInfo.tagProperty = tagProperty
        // 参数
         const _param = {}
         this.editList.forEach(args =>{
              _param[args.key] = args.value
         })
         Object.assign( this.tagInfo , _param )
         console.log(this.tagInfo.tagProperty)
        //发起网络请求
         const [res] = await asyncApiFun( addOrUpdate ,this.tagInfo )
         if (res) {
            this.$router.push({path:'/member/setTag'})
         }

      },
      // 返回
      goBack(){
        this.$router.push({path:'/member/setTag'})
      }
    },
    computed: {
      getdata() {
        function getTags(arr) {
          const tags = []
          arr.forEach(item => {
            if( item.key !== 'gender') {
              if(item.key=='city'){
                item.dynamicTags.forEach( city => {
                    const obj = {
                        key:city.key,
                        cityName:city.name,
                        p : item,
                        name:city.name,
                        areaProvinceId:city.areaProvinceId,
                        areaCityId:city.areaCityId,
                        areaDistrictId:city.areaDistrictId
                      }
                        tags.push(obj)
                        // console.log(item)
                    })
                }else {
                    item.dynamicTags.forEach(item2 => {
                        const obj = {
                        p : item,
                        key : item.key,
                        name : item2.name instanceof Array ? item2.name[1] : item2.name ,
                        operator: item2.operator,
                        term : item2.term
                        }
                        tags.push(obj)
                    })
                 }    
              }    
            else {
              const _data = item.getValue()
              if (_data) {
                _data.delete = () => item.delete();
                tags.push(_data)
              }
              else {
                item.dynamicTags.forEach(item3 => {
                  const obj = {
                    p : item,
                    key : item.key,
                    name : item3.name ,
                    operator: item3.operator,
                    term : item3.term
                  }
                  tags.push(obj)
              })
              } 
            }
          })
          return tags;
        }
        return [
          {label:'用户属性：' ,key: 'userProperty' , value: this.userProperty, tags: getTags(this.userProperty)},
          {label:'行为属性：' ,key: 'actionProperty', value: this.actionProperty, tags: getTags(this.actionProperty) },
          {label:'商务属性：' ,key: 'businessProperty' , value: this.businessProperty, tags: getTags(this.businessProperty)},
        ]
      },
      // 获取标签类型的值
      getRadioVal(){
        let radioVal = "0"
        this.editList.forEach( item => {
          if( item.key =='tagType' ) radioVal = item.value
        })
        return radioVal
      }
     
    }


  }
</script>

        
<style lang="scss" scoped>
.addLabel{
  background-color: #FFFFFF;
  width:90%;
  margin: 20px auto;
}
.content-box{
  width:60%;
  margin: 0 auto;
  padding-top:40px;
  }
  .tw{
    height: 200px;
  }
  .el-row{
    display: block;
    width:100%;
    text-align: center;
    margin-top:120px;
    padding: 20px 0;
    border-top:1px solid #eee;
  }
  .tag-box{
    margin-left: 10px;
   
  }
  .tag-item{
     margin-right: 10px;
  }
</style>